﻿using Brc_DSB.WebService.WebServiceHelper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Exceptionless;
using System.IO;
using System.Threading.Tasks;

namespace Brc_DSB.ServiceForward.Controllers
{
    public class HomeController : Controller
    {
        public JsonResult Health()
        {
            return Json("OK", JsonRequestBehavior.AllowGet);
        }
        public ActionResult Index()
        {
            return View();
        }

        public async Task<object> CallWebService()
        {
            try
            {
                var stringParamter = string.Empty;
                var dataStream = HttpContext.Request.GetBufferlessInputStream();
                using (var st = new StreamReader(dataStream))
                {
                    stringParamter = await st.ReadToEndAsync();
                }                               
                var paramters = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(stringParamter);
                var array = new List<object>();
                foreach (var item in paramters)
                {
                    var value = item.Value;
                    if(value.GetType().Name=="JArray")
                    {
                        array.Add($"[{string.Join(",", item.Value)}]");
                    }
                    else
                    {
                        array.Add(value.Value);
                    }
                }
                var className = Request.Headers["ClassName"].ToString();
                var methodName = Request.Headers["MethodName"].ToString();
                var serviceAddress = Request.Headers["ServiceAddress"].ToString();
                var client = new WebServiceCall(serviceAddress);
                var result = client?.Invoke<object>(className, methodName, array.ToArray());
                return result;
            }
            catch (Exception e)
            {
                ExceptionlessClient.Default.CreateException(e).Submit();
                return null;
            }

        }

    }
}